package com.cjc.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cjc.domain.Device;
import com.cjc.mapper.DeviceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: 陈江灿
 * @CreateTime: 2025-01-21
 */
@Service
public class DeviceService {

    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 查询设备
     *
     * @param deviceId 设备主键
     * @return 设备
     */
    public Device selectDeviceByDeviceId(Long deviceId){
        return deviceMapper.selectById(deviceId);
    }

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备集合
     */
    public List<Device> selectDeviceList(Device device) {
        QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
        if (device.getDeviceName() != null) {
            queryWrapper.lambda().eq(Device::getDeviceName, device.getDeviceName());
        }
        return deviceMapper.selectList(queryWrapper);
    }

    /**
     * 新增设备
     *
     * @param device 设备
     * @return 结果
     */
    public int insertDevice(Device device){
        device.setUrl(this.generateRtspUrl(device));
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备
     *
     * @param device 设备
     * @return 结果
     */
    public int updateDevice(Device device){
        device.setUrl(this.generateRtspUrl(device));
        return deviceMapper.updateById(device);
    }

    /**
     * 删除设备信息
     *
     * @param deviceId 设备主键
     * @return 结果
     */
    public int deleteDeviceByDeviceId(Long deviceId){
        return deviceMapper.deleteById(deviceId);
    }


    /**
     * 生成rtsp地址
     * @param device
     * @return
     */
    private String generateRtspUrl(Device device) {
        String ip = device.getIp();
        String userName = device.getUserName();
        String password = device.getPassword();
        int port = 554;

        if ("1".equals(device.getType())) {
            return String.format("rtsp://%s:%s@%s:%d/Streaming/Channels/2", userName, password, ip, port);
        } else if ("2".equals(device.getType())) {
            return String.format("rtsp://%s:%s@%s:%d/cam/realmonitor?channel=1&subtype=0", userName, password, ip, port);
        } else {
            throw new RuntimeException("网络异常，请检查网络！");
        }
    }

}
